<?php
namespace Appstore\Widget;

use Think\Controller;

class PriceWidget extends Controller
{

    public function render($goods)
    {
        $versions = D('AppstoreVersion')->where(array('goods_id' => $goods['id'], 'status' => 1))->order('create_time desc')->select();
        if (empty($versions)) {
            $this->display(T('Application://Appstore@Widget/price_empty'));
            return;
        } else {
            $version = $versions[0];
            if ($version['need_buy'] == 0) {
                $this->display(T('Application://Appstore@Widget/price_free'));
                return;
            } else {
                $scores = D('Ucenter/Score')->getTypeList();
                $uid = get_uid();
                $role_id = get_role_id($uid);
                foreach ($scores as $s) {
                    $scoreList[$s['id']] = $s;
                }
                $prices = D('AppstorePrice')->where(array('version_id' => $version['id'], 'pid' => 0))->order('id asc')->select();
                foreach ($prices as $key => &$price) {
                    $price['score'] = $scoreList[$price['value']];
                    $price['children'] = D('AppstorePrice')->where(array('version_id' => $version['id'], 'pid' => $price['id']))->order('id asc')->select();
                    if ($key == 0) {
                        //第一个
                        if (empty($price['children'])) {
                            $firstPrice=$price['price'].$price['score']['unit'];
                        }
                    }
                    foreach ($price['children'] as $key_child=>&$child) {
                        if($child['key']=='role' ){
                            if($child['value']!=$role_id){
                                unset($price['children'][$key_child]);
                                continue;
                            }
                        }

                        if ($child['price_type'] != 'price') {
                            $child['computed_price'] = $child['price'] * $price['price'] / 100;
                            $child['text'] = $child['price'] / 10;
                        } else {
                            $child['computed_price'] = $child['price'];
                        }
                        if($key_child==0 && empty($firstPrice)){
                            $firstPrice=$child['computed_price'].$price['score']['unit'] ;
                        }
                    }

                }
            }
            $this->assign('firstPrice',$firstPrice);
            $this->assign('price', $prices);
            $this->display(T('Application://Appstore@Widget/price'));
        }

    }

}